#include "osal_mutex.h"

int osal_mutex_init(osal_mutex_t *m, char *name)
{
#if defined(OSAL_USE_OS)
    if (m == NULL) return -1;
    m->mutex = rt_mutex_create(name, RT_IPC_FLAG_PRIO);
    if (m->mutex == RT_NULL) return -2;
#endif
    return 0;
}

int osal_mutex_lock(osal_mutex_t *m)
{
#if defined(OSAL_USE_OS)
    if (m == NULL || m->mutex == RT_NULL) return -1;
    return rt_mutex_take((m->mutex), RT_WAITING_FOREVER);
#else
    return 0;
#endif
}

int osal_mutex_trylock(osal_mutex_t *m)
{
#if defined(OSAL_USE_OS)
    if (m == NULL || m->mutex == RT_NULL) return -1;
    return rt_mutex_take((m->mutex), 0);
#else
    return 0;
#endif
}

int osal_mutex_unlock(osal_mutex_t *m)
{
#if defined(OSAL_USE_OS)
    if (m == NULL || m->mutex == RT_NULL) return -1;
    return rt_mutex_release((m->mutex));
#else
    return 0;
#endif
}

int osal_mutex_destroy(osal_mutex_t *m)
{
#if defined(OSAL_USE_OS)
    if (m == NULL || m->mutex == RT_NULL) return -1;
    return rt_mutex_delete((m->mutex));
#else
    return 0;
#endif
}
